package com.atl.controller.web;

import cn.hutool.core.io.FileUtil;

import java.io.File;
import java.util.Arrays;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


import com.atl.common.BaseResponse;
import com.atl.common.ErrorCode;
import com.atl.constant.FileConstant;
import com.atl.enity.enums.FileUploadBizEnum;
import com.atl.enity.web.dto.file.UploadFileRequest;
import com.atl.execption.BusinessException;
import com.atl.manager.CosManager;
import com.atl.service.IAdminUserService;
import com.atl.service.IAdvertisementService;
import com.google.gson.Gson;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


@RestController
@RequestMapping("/web/file")
@Api(tags = "文件管理")
@Slf4j
public class FileController {

    @Resource
    private IAdvertisementService advertisementService;

    @Resource
    private CosManager cosManager;

    /**
     * 文件上传
     *
     * @param multipartFile
     * @param uploadFileRequest
     * @param request
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public BaseResponse<String> uploadFile(@RequestPart("file") MultipartFile multipartFile,
                                           UploadFileRequest uploadFileRequest, HttpServletRequest request) {
        String biz = uploadFileRequest.getBiz();
        FileUploadBizEnum fileUploadBizEnum = FileUploadBizEnum.getEnumByValue(biz);
        if (fileUploadBizEnum == null) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        validFile(multipartFile, fileUploadBizEnum);
        //IAdvertisementService loginUser = advertisementService.getLoginUser(request);
        // 文件目录：根据业务、用户来划分
        String uuid = RandomStringUtils.randomAlphanumeric(8);
        String filename = uuid + "-" + multipartFile.getOriginalFilename();
        String filepath = String.format("/%s/%s", fileUploadBizEnum.getValue(), filename);
        File file = null;
        try {
            Configuration cfg = new Configuration(Region.region2());

            UploadManager uploadManager = new UploadManager(cfg);
            // 生成上传凭证，然后准备上传
            Auth auth = Auth.create("TLB20O2gPcCjrYXv_sRtzHZthXhzDgWdgmo76ikx", "wEcZo_Zfj_TxuzkZ4s-4C7bFVmrjzXz4afh_aFIB");
            String upToken = null;
            String path = null;

            upToken = auth.uploadToken("saredchargingpile");
            path = filepath;

            Response response = uploadManager.put(multipartFile.getInputStream(), null, upToken, null, null);
            // 解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                //return path + putRet.key;

            // 返回可访问地址
            return BaseResponse.okResult(FileConstant.COS_HOST + "/" + putRet.key );
        } catch (Exception e) {
            log.error("file upload error, filepath = " + filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            if (file != null) {
                // 删除临时文件
                boolean delete = file.delete();
                if (!delete) {
                    log.error("file delete error, filepath = {}", filepath);
                }
            }
        }
    }

    // zone0华东区域,zone1是华北区域,zone2是华南区域
    //Configuration cfg = new Configuration(Region.region0());
    //UploadManager uploadManager = new UploadManager(cfg);
    //// 生成上传凭证，然后准备上传
    //Auth auth = Auth.create(Constant.accessKey, Constant.secretKey);
    //String upToken = null;
    //String path = null;
    //    if (fileType.equals(Constant.IMAGE)) {
    //    upToken = auth.uploadToken(Constant.bucketPictureName);
    //    path = Constant.domainPicture;
    //} else if (fileType.equals(Constant.FILE)) {
    //    upToken = auth.uploadToken(Constant.bucketFileName);
    //    path = Constant.domainFile;
    //}
    //Response response = uploadManager.put(file, null, upToken, null, null);
    //// 解析上传成功的结果
    //DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
    //    return path + putRet.key;


    /**
     * 校验文件
     *
     * @param multipartFile
     * @param fileUploadBizEnum 业务类型
     */
    private void validFile(MultipartFile multipartFile, FileUploadBizEnum fileUploadBizEnum) {
        // 文件大小
        long fileSize = multipartFile.getSize();
        // 文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final long ONE_M = 1024 * 1024L;
        if (FileUploadBizEnum.USER_AVATAR.equals(fileUploadBizEnum)) {
            if (fileSize > ONE_M) {
                throw new BusinessException(-1, "文件大小不能超过 1M");
            }
            if (!Arrays.asList("jpeg", "jpg", "svg", "png", "webp").contains(fileSuffix)) {
                throw new BusinessException(-1, "文件类型错误");
            }
        }
    }
}
